<template>
  <div class="page-container main-view">
    <el-row
      :gutter="0"
      v-show="dataContainer.showSearch"
      class="page-query-box"
    >
      <el-col :span="24" :xs="24">
        <el-form
          :model="dataContainer.form"
          ref="QueryFormRef"
          :inline="true"
          label-width="110px"
        >
          <el-row :gutter="0">
            <el-col :span="6" :xs="6">
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="dataContainer.form.username"
                  placeholder="请输入用户名"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="真实姓名" prop="realName">
                <el-input
                  v-model="dataContainer.form.realName"
                  placeholder="请输入真实姓名"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="审核状态" prop="verified">
                <el-select
                  v-model="dataContainer.form.verified"
                  placeholder="请选择审核状态"
                  clearable
                  @clear="handleQuery"
                >
                  <el-option label="待审核" :value="false" />
                  <el-option label="已审核" :value="true" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label=" ">
                <el-button type="primary" @click="handleQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:search-bt.svg"
                  ></SvgIcon>
                  查询
                </el-button>
                <el-button @click="resetQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:redo.svg"
                  ></SvgIcon>
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <div class="table-box content-container page-content-box">
      <div class="top-container">
        <div class="left">
          <el-button
            type="primary"
            :disabled="dataContainer.list.length === 0"
            @click="handleBatchVerify(true)"
          >
            批量通过
          </el-button>
        </div>
        <div class="right">
          <el-button circle @click="resetQuery">
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:redo.svg"
            ></SvgIcon>
          </el-button>
          <el-button
            circle
            @click="dataContainer.showSearch = !dataContainer.showSearch"
          >
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:search-bt.svg"
            ></SvgIcon>
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="dataContainer.loading"
          :data="dataContainer.list"
          border
          @selection-change="handleSelectionChange"
          @cell-dblclick="handleCopyValue"
          height="100%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
            fixed="left"
          />
          <el-table-column
            label="用户名"
            show-overflow-tooltip
            align="center"
            min-width="120"
          >
            <template #default="scope">
              {{ scope.row.userId?.username || "-" }}
            </template>
          </el-table-column>
          <el-table-column
            label="真实姓名"
            show-overflow-tooltip
            align="center"
            min-width="120"
            prop="realName"
          />
          <el-table-column
            label="身份证号"
            show-overflow-tooltip
            align="center"
            min-width="180"
            prop="idNumber"
          />
          <el-table-column
            label="审核状态"
            show-overflow-tooltip
            align="center"
            min-width="100"
          >
            <template #default="scope">
              <el-tag :type="scope.row.verified ? 'success' : 'warning'">
                {{ scope.row.verified ? "已审核" : "待审核" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="提交时间"
            show-overflow-tooltip
            align="center"
            min-width="170"
            prop="createdAt"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="180"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                :text="true"
                type="primary"
                v-if="!scope.row.verified"
                @click="handleVerify(scope.row, true)"
              >
                审核
              </el-button>
              <el-button
                :text="true"
                v-if="scope.row.verified"
                @click="handleDetails(scope.row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          v-show="true"
          :total="dataContainer.config.total"
          :background="true"
          :current-page="dataContainer.params.page"
          :page-size="dataContainer.params.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :pager-count="7"
          @size-change="
            (size) => {
              dataContainer.params.limit = size;
              getDataList();
            }
          "
          @current-change="
            (page) => {
              dataContainer.params.page = page;
              getDataList();
            }
          "
        />
      </div>
    </div>
    <VerifyDialog ref="VerifyDialogRef"></VerifyDialog>
  </div>
</template>

<script>
/**
 * 实名认证审核页面
 */
import {
  defineComponent,
  onBeforeUnmount,
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  onMounted,
} from "vue";
import { useRouter } from "vue-router";
import { copyValue } from "@/common/OtherTools";
import { debounceFn } from "@/common/DebounceAndThrottle";
import {
  messageSuccess,
  messageError,
  confirm,
} from "@/action/MessagePrompt.js";
import SvgIcon from "@/components/svgIcon/index.vue";
import { hasPermi } from "@/action/PowerTools";
import verificationsApi from "@/http/verifications.js";
import VerifyDialog from "./components/VerifyDialog.vue";
import { ElMessageBox } from "element-plus";

export default defineComponent({
  components: {
    SvgIcon,
    VerifyDialog,
  },
  setup() {
    onMounted(() => {
      getDataList();
    });

    const VerifyDialogRef = ref(null);
    const router = useRouter();
    const dataContainer = reactive({
      loading: false,
      showSearch: true,
      form: {
        verified: false, // 默认显示待审核的
      },
      params: {
        page: 1,
        limit: 10,
      },
      config: {
        total: 0,
      },
      list: [],
      selectedList: [],
    });

    /** 格式化日期时间 */
    function formatDateTime(dateTime) {
      if (!dateTime) return "-";
      const date = new Date(dateTime);
      return date.toLocaleString();
    }

    /** 获取数据列表 */
    const getDataList = debounceFn(function () {
      dataContainer.loading = true;

      // 构建查询参数
      const params = {
        page: dataContainer.params.page,
        limit: dataContainer.params.limit,
        verified: dataContainer.form.verified,
      };

      // 添加用户名和真实姓名筛选
      if (dataContainer.form.username) {
        params.username = dataContainer.form.username;
      }
      if (dataContainer.form.realName) {
        params.realName = dataContainer.form.realName;
      }

      verificationsApi
        .getVerifications(params)
        .then((res) => {
          if (res.data && res.data.verifications) {
            dataContainer.list = res.data.verifications;
            dataContainer.config.total = res.data.pagination.total;
          } else {
            dataContainer.list = [];
            dataContainer.config.total = 0;
          }
        })
        .catch((err) => {
          console.error("获取实名认证列表失败", err);
          messageError(err.message || "获取实名认证列表失败");
        })
        .finally(() => {
          dataContainer.loading = false;
        });
    }, 300);

    /** 表格选择项改变 */
    function handleSelectionChange(selection) {
      dataContainer.selectedList = selection;
    }

    /** 双击单元格，复制单元格内容 */
    function handleCopyValue(_, __, ___, event) {
      copyValue(event.target.innerText);
      messageSuccess("复制成功，内容为：" + event.target.innerText);
    }

    /** 搜索按钮操作 */
    function handleQuery() {
      dataContainer.params.page = 1;
      getDataList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
      dataContainer.form = {
        verified: false, // 默认显示待审核的
      };
      handleQuery();
    }

    /** 查看详情按钮操作 */
    function handleDetails(row) {
      if (!VerifyDialogRef.value) return;

      VerifyDialogRef.value.initData(true, row, {
        isShow: true,
        afterTitle: " - 详情",
      });
    }

    /** 审核操作 */
    function handleVerify(row, isApproved) {
      if (!VerifyDialogRef.value) return;

      // 获取认证记录ID
      const verificationId = row.id || row._id;
      if (!verificationId) {
        messageError("无法获取认证记录ID");
        return;
      }

      // 打开审核对话框
      VerifyDialogRef.value
        .initData(true, row, {
          isApproved: isApproved,
          afterTitle: isApproved ? " - 审核通过" : " - 审核拒绝",
        })
        .then(() => {
          getDataList();
        })
        .catch(() => {});
    }

    /** 批量审核通过 */
    function handleBatchVerify(isApproved) {
      if (dataContainer.selectedList.length === 0) {
        messageError("请先选择要审核的记录");
        return;
      }

      ElMessageBox.confirm(
        `确定要批量通过所选的 ${dataContainer.selectedList.length} 条实名认证记录吗？`,
        "批量审核确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "success",
        }
      )
        .then(() => {
          const verificationIds = dataContainer.selectedList
            .map((item) => item.id || item._id)
            .filter((id) => id);
          if (verificationIds.length === 0) {
            messageError("无法获取认证记录ID");
            return;
          }

          dataContainer.loading = true;

          // 批量处理
          const verifyPromises = verificationIds.map((id) =>
            verificationsApi.verifyUser(id, { verified: true })
          );

          Promise.all(verifyPromises)
            .then(() => {
              messageSuccess(`已批量通过 ${verificationIds.length} 条实名认证`);
              getDataList();
            })
            .catch((err) => {
              console.error("批量审核失败", err);
              messageError(err.message || "批量审核失败");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        })
        .catch(() => {
          // 用户取消操作
        });
    }

    return {
      dataContainer,
      getDataList,
      handleCopyValue,
      handleQuery,
      resetQuery,
      handleDetails,
      handleVerify,
      handleBatchVerify,
      handleSelectionChange,
      formatDateTime,
      VerifyDialogRef,
    };
  },
});
</script>

<style lang="scss" scoped>
.main-view {
  display: flex;
  flex-direction: column;
  > .page-query-box {
    margin: 0 0 10px 0 !important;
    padding: 10px 10px 0px 10px;
    :deep(.el-form-item) {
      margin-bottom: 10px !important;
    }
    :deep(.el-form-item--default) {
      width: 100%;
      margin-right: 0;
    }
  }
  > .content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 10px 10px;
    box-sizing: border-box;
    background: #fff;
    > .top-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0px 0 10px 0;
    }
    > .table-container {
      flex: 1 1 auto;
      height: 0;
      overflow: auto;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 0;
    margin: 10px 0 0 0;
  }
}
</style> 